package com.hollowlatte.manage.controller;

import com.hollowlatte.common.utils.Result;
import com.hollowlatte.manage.entity.User;
import com.hollowlatte.manage.entity.vo.UserVO;
import com.hollowlatte.manage.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

/**
 * @author Hollow Latte
 * @date 2021/5/24 22:17
 */
@Tag(name = "AuthenticationController", description = "验证管理")
@CrossOrigin
@RestController
@RequestMapping("")
public class AuthenticationController {
    private final UserService userService;

    public AuthenticationController(UserService userService) {
        this.userService = userService;
    }


    @Operation(summary = "登录")
    @PostMapping("login")
    public Result login(@RequestBody UserVO userVO) {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute("username", userVO.getId());
        subject.login(new UsernamePasswordToken(userVO.getId().toString(), userVO.getPassword()));

        User user = userService.getById(userVO.getId());
        UserVO resultUserVO = userService.convertUserToUserVO(user);
        return Result.ok().data("user", resultUserVO);
    }


    @Operation(summary = "登出")
    @GetMapping("logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return Result.ok();
    }


    @Operation(summary = "修改用户密码")
    @PutMapping("password")
    public Result modifyPassword(@RequestBody UserVO userVO) {
        User user = new User();
        user.setId(userVO.getId());
        user.setPassword(userVO.getPassword());

        boolean affect = userService.updatePassword(user);

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }
}